﻿using Infrastructure.ElasticSearch.Configuration;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;

namespace Infrastructure.ElasticSearch
{
    public static class ElasticSearchRegistrar
    {
        public static IServiceCollection AddElasticSearch(this IServiceCollection services, IConfiguration configuration, Action<ElasticSearchConfig> config = null)
        {
            var esConfig = new ElasticSearchConfig();

            config?.Invoke(esConfig);

            configuration.GetSection(nameof(ElasticSearchConfig)).Bind(esConfig);

            if (string.IsNullOrWhiteSpace(esConfig.ConnectionStrings))
                throw new ArgumentNullException(nameof(esConfig.ConnectionStrings));

            services.AddSingleton<ElasticSearchConfig>(service => esConfig);

            return services;
        }
    }
}
